using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class ObjectPoolComponent : BaseComponent
{
    public GameObject ObjectPrefab;

    public Queue<GameObject> pool = new Queue<GameObject>();
    public List<GameObject> OpenObjectList = new List<GameObject>();

    public GameObject CreateNewObject(bool IsActive)
    {
        GameObject go = MonoBehaviour.Instantiate(ObjectPrefab);
        go.gameObject.SetActive(IsActive);
        if (!IsActive)
        {
            pool.Enqueue(go);
        }
        return go;
    }

    public GameObject SpawnObject(Vector3 position, Quaternion rotation)
    {
        GameObject go = null;
        // 检查对象池中是否有可用对象
        if (pool.Count > 0)
        {
            go = pool.Dequeue();
            go.transform.position = position;
            // 添加随机Y轴旋转
            go.transform.rotation = rotation;
            go.gameObject.SetActive(true);
            // gold.gameObject.transform.localScale = Vector3.one;
        }
        else
        {
            // 如果对象池为空，创建新对象
            go = CreateNewObject(true);
            go.transform.position = position;
            // 添加随机Y轴旋转
            go.transform.rotation = rotation;
        }
        OpenObjectList.Add(go);
        Entity entity = go.GetComponent<Entity>();
        if (entity != null)
        {
            entity.objectPoolComponentReference = this;
        }
        // TestWood.Add(wood);
        return go;
    }

    public void Recycle(GameObject go)
    {
        if (go != null)
        {
            go.gameObject.SetActive(false);
            pool.Enqueue(go);
            // TestWood.Remove(wood);
            OpenObjectList.Remove(go);
            go.transform.parent = null;
        }
    }

    public void RecycleAll()
    {
        foreach (var go in OpenObjectList)
        {
            go.gameObject.SetActive(false);
            pool.Enqueue(go);
            go.transform.parent = null;
        }
        OpenObjectList.Clear();
    }
}
